#include <thread>
#include <vector>
#include <random>
#include <atomic>
#include <chrono>
#include <iostream>
#include <csignal>
#include <cstdlib>
#include "../../common/detail.hpp"
#include "../../client/rpc_client.hpp"

using namespace std::chrono_literals;

static const char* kMethods[] = {
    "Add", "Subtract", "Multiply", "Divide", "Mold"
};

static std::atomic<bool> stop{false};
static std::atomic<bool> signal_handled{false};
static auto start_time = std::chrono::steady_clock::now();

void signal_handler(int sig) {
    if (sig == SIGINT || sig == SIGTERM) {
        // 确保信号只处理一次
        bool expected = false;
        if (!signal_handled.compare_exchange_strong(expected, true)) {
            return; // 已经处理过了
        }
        
        auto end_time = std::chrono::steady_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
        
        std::cout << "\n=== 收到退出信号 ===" << std::endl;
        std::cout << "客户端1测试时长: " << duration.count() << " 秒" << std::endl;
        std::cout << "正在安全关闭客户端，请稍候..." << std::endl;
        
        stop.store(true);
        
        // 给工作线程一些时间来检查stop标志并输出统计
        std::this_thread::sleep_for(std::chrono::seconds(2));
    }
}

int main(){
    myrpc::initLoggers();
    
    // 注册信号处理
    std::signal(SIGINT, signal_handler);
    std::signal(SIGTERM, signal_handler);
    
    std::cout << "=== 启动RPC客户端1 高并发压力测试 ===" << std::endl;
    std::cout << "连接到服务注册中心: 127.0.0.1:28080" << std::endl;
    
    auto client = std::make_shared<myrpc::client::RpcClient>(true, "127.0.0.1", 28080);
    
    std::vector<std::thread> workers;
    std::mt19937 rng{std::random_device{}()};
    
    // 工作线程函数
    auto do_work = [&](int thread_id){
        std::uniform_int_distribution<int> method_dis(0, 4);
        std::uniform_int_distribution<int> value_dis(1, 100);
        std::uniform_int_distribution<int> call_dis(0, 2); // 0=同步, 1=异步, 2=回调
        
        int success_count = 0;
        int error_count = 0;
        
        while(!stop.load()){
            try {
                std::string method = kMethods[method_dis(rng)];
                int a = value_dis(rng);
                int b = value_dis(rng);
                if (method == "Divide" || method == "Mold") {
                    b = std::max(1, b); // 避免除零
                }
                
                Json::Value params;
                params["num1"] = a;
                params["num2"] = b;
                
                int call_type = call_dis(rng);
                bool success = false;
                
                if (call_type == 0) {
                    // 同步调用
                    Json::Value result;
                    success = client->call(method, params, result);
                    if (success) {
                        success_count++;
                    }
                } else if (call_type == 1) {
                    // 异步调用
                    myrpc::client::RpcCaller::JsonRspFuture fut;
                    if (client->call(method, params, fut)) {
                        try {
                            // 给future.get()加超时，避免永久等待
                            if (fut.wait_for(std::chrono::seconds(5)) == std::future_status::ready) {
                                auto result = fut.get();
                                success = true;
                                success_count++;
                            } else {
                                // 超时视为错误
                                error_count++;
                            }
                        } catch (...) {
                            error_count++;
                        }
                    }
                } else {
                    // 回调调用
                    auto cb = [&success_count](const Json::Value &res) { 
                        success_count++;
                    };
                    success = client->call(method, params, cb);
                }
                
                if (!success) {
                    error_count++;
                }
                
                // 每1000次调用输出一次状态
                if ((success_count + error_count) % 1000 == 0) {
                    std::cout << "线程" << thread_id << " - 成功:" << success_count 
                              << " 错误:" << error_count << std::endl;
                }
                
            } catch (...) {
                error_count++;
            }
            
            // 调用间隔200ms，与服务重启节奏更匹配
            std::this_thread::sleep_for(200ms);
        }
        
        std::cout << "线程" << thread_id << "结束 - 总成功:" << success_count 
                  << " 总错误:" << error_count << std::endl;
    };
    
    // 启动12个工作线程，高并发压力
    int thread_num = 12;
    std::cout << "启动 " << thread_num << " 个工作线程..." << std::endl;
    for (int i = 0; i < thread_num; i++) {
        workers.emplace_back(do_work, i + 1);
    }
    
    // 等待信号或工作线程结束
    for (auto &t : workers) {
        if (t.joinable()) {
            if (stop.load()) {
                // 如果是信号触发的退出，快速分离线程
                t.detach();
            } else {
                t.join();
            }
        }
    }
    
    std::cout << "客户端1测试完成!" << std::endl;
    
    // 信号退出时强制快速结束
    if (stop.load()) {
        std::cout << "强制快速退出" << std::endl;
        std::_Exit(0);  // 快速退出，避免析构卡住
    }
    
    mylog::shutdown();
    return 0;
}
